package com.lagou.edu.mvcFramework.servlet;

import com.lagou.edu.mvcFramework.annotations.*;
import com.lagou.edu.mvcFramework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author stevejson
 */
public class MyDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private Map<String, Object> ioc = new HashMap<>();

    private List<String> classNames = new ArrayList<>();

    //private Map<String, Method> handlerMapping = new HashMap<>();

    private List<Handler> handlerMapping = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    /**
     * 处理请求
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        Object[] paraValues = new Object[parameterTypes.length];

        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            String join = StringUtils.join(stringEntry.getValue(), ",");
            if (!handler.getParamIndexMapping().containsKey(stringEntry.getKey())) {
                continue;
            }

            //有这个参数
            Integer integer = handler.getParamIndexMapping().get(stringEntry.getKey());
            paraValues[integer] = join;


        }

        Integer integer = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[integer] = resp;
        Integer integer1 = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[integer1] = req;
        String result = "";
        try {
            Object response = handler.invoke(req.getParameter("username"), paraValues);
            if (response != null) {
                result = (String) response;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = e.getMessage();
        } finally {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write(result);
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {
            return null;
        }
        String uri = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(uri);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }

        return null;


    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //加载配置文件
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        //扫描注解
        doScan(properties.getProperty("scanPackage"));
        //初始化bean
        doInstance();
        //autowired
        doAutowired();
        //处理器映射器
        initHandlerMapping();

        System.out.println("自定义初始化完成。。。");
    }

    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> stringObjectEntry : ioc.entrySet()) {
            Class<?> aClass = stringObjectEntry.getValue().getClass();
            if (!aClass.isAnnotationPresent(MyController.class)) {
                continue;
            }
            String baseUrl = "";
            if (aClass.isAnnotationPresent(MyRequestMapping.class)) {
                MyRequestMapping annotation = aClass.getAnnotation(MyRequestMapping.class);
                baseUrl = annotation.value();
            }

            //类上的security判定
            String[] baseUserNames = new String[0];
            if (aClass.isAnnotationPresent(Security.class)) {
                Security annotation = aClass.getAnnotation(Security.class);
                baseUserNames = annotation.value();
            }

            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                Set<String> permissionUsername = new HashSet<>(Arrays.asList(baseUserNames));
                if (!method.isAnnotationPresent(MyRequestMapping.class)) {
                    return;
                }
                //method上的security判断
                if (method.isAnnotationPresent(Security.class)) {
                    Security annotation = method.getAnnotation(Security.class);
                    String[] userNames = annotation.value();
                    permissionUsername.addAll(Arrays.asList(userNames));
                }
                MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
                String methodUrl = annotation.value();
                String url = baseUrl + methodUrl;
                Handler handler = new Handler(stringObjectEntry.getValue(), method, Pattern.compile(url), permissionUsername);
                //计算参数信息
                Parameter[] parameters = method.getParameters();
                Integer i = 0;
                for (Parameter parameter : parameters) {

                    if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), i);
                    } else {
                        //普通类型
                        handler.getParamIndexMapping().put(parameter.getName(), i);
                    }
                    i += 1;


                }
                handlerMapping.add(handler);
            }


        }


    }

    private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> stringObjectEntry : ioc.entrySet()) {
            Field[] declaredFields = stringObjectEntry.getValue().getClass().getDeclaredFields();

            for (Field declaredField : declaredFields) {
                if (!declaredField.isAnnotationPresent(MyAutowired.class)) {
                    continue;
                }

                MyAutowired annotation = declaredField.getAnnotation(MyAutowired.class);
                String beanName = annotation.value();
                if ("".equals(beanName.trim())) {
                    beanName = declaredField.getType().getName();
                }

                declaredField.setAccessible(true);
                try {
                    declaredField.set(stringObjectEntry.getValue(), ioc.get(beanName));

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("自动注入失败");
                }
            }
        }

    }

    private void doInstance() {
        if (classNames.size() == 0) {
            return;
        }
        try {
            for (String className : classNames) {
                Class<?> aClass = Class.forName(className);
                if (aClass.isAnnotationPresent(MyController.class)) {
                    String simpleName = aClass.getSimpleName();
                    String lowerFirst = toLowerFirst(simpleName);
                    Object instance = aClass.getDeclaredConstructor().newInstance();
                    ioc.put(lowerFirst, instance);

                } else if (aClass.isAnnotationPresent(MyService.class)) {
                    MyService annotation = aClass.getAnnotation(MyService.class);
                    String beanName = annotation.value();
                    if (!"".equals(beanName.trim())) {
                        ioc.put(beanName, aClass.newInstance());
                    } else {
                        ioc.put(toLowerFirst(aClass.getSimpleName()), aClass.newInstance());
                    }

                    //service层接口名作为id在存储一份，便于注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("实例化对象失败");
        }
    }

    private String toLowerFirst(String string) {
        char[] chars = string.toCharArray();
        char upperA = 'A';
        char upperZ = 'Z';
        if (upperA <= chars[0] && chars[0] <= upperZ) {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }


    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                doScan(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }


        }

    }

    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            assert resourceAsStream != null;
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取properties fail:" + contextConfigLocation);
        }
    }


}
